from fastapi import APIRouter, Request, Form, Depends, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
import json
import os
import logging

# 配置日志
logger = logging.getLogger(__name__)

# 创建路由
router = APIRouter()

# 初始化模板
current_dir = os.path.dirname(os.path.abspath(__file__))
templates = Jinja2Templates(directory=os.path.join(current_dir, "templates"))

# 配置文件路径
CONFIG_FILE = os.path.join(current_dir, "db_config.json")

# 获取当前配置
def get_current_config():
    """
    读取并返回当前的数据库配置
    """
    try:
        if os.path.exists(CONFIG_FILE):
            with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
    except Exception as e:
        logger.error(f"读取配置文件失败: {str(e)}")
    
    # 返回默认配置
    return {
        "db_type": "mysql",
        "sqlite_path": os.path.join(current_dir, "trade_monitor.db"),
        "mysql_host": "192.168.127.12",
        "mysql_port": 3306,
        "mysql_user": "remote_admin",
        "mysql_password": "Admin@szlwy68",
        "mysql_db_name": "trade_monitor",
        "tq_username": "cps168",
        "tq_password": "alibaba"
    }

# 数据库配置编辑页面
@router.get("/database_config", response_class=HTMLResponse)
async def database_config_form(request: Request):
    """
    显示数据库配置编辑页面
    """
    config = get_current_config()
    return templates.TemplateResponse(
        "database_config.html",
        {
            "request": request,
            "config": config,
            "error": None
        }
    )

# 数据库配置编辑器页面
@router.get("/db_config_editor", response_class=HTMLResponse)
async def db_config_editor_form(request: Request):
    """
    显示数据库配置编辑器页面
    """
    config = get_current_config()
    return templates.TemplateResponse(
        "db_config_editor.html",
        {
            "request": request,
            "config": config,
            "message": None
        }
    )

# 保存数据库配置
@router.post("/save_database_config")
async def save_database_config(
    request: Request,
    db_type: str = Form(...),
    sqlite_path: str = Form(None),
    mysql_host: str = Form(None),
    mysql_port: str = Form(None),
    mysql_user: str = Form(None),
    mysql_password: str = Form(None),
    mysql_db_name: str = Form(None),
    tq_username: str = Form(None),
    tq_password: str = Form(None)
):
    """
    保存数据库配置到配置文件
    """
    try:
        # 构建配置对象
        config = {
            "db_type": db_type,
            "tq_username": tq_username or "",
            "tq_password": tq_password or ""
        }
        
        # 根据数据库类型添加相应配置
        if db_type == "sqlite":
            config["sqlite_path"] = sqlite_path or os.path.join(current_dir, "trade_monitor.db")
        elif db_type == "mysql":
            config["mysql_host"] = mysql_host or "192.168.127.12"
            config["mysql_port"] = int(mysql_port) if mysql_port else 3306
            config["mysql_user"] = mysql_user or "remote_admin"
            config["mysql_password"] = mysql_password or ""
            config["mysql_db_name"] = mysql_db_name or "trade_monitor"
        
        # 保存配置文件
        with open(CONFIG_FILE, "w", encoding="utf-8") as f:
            json.dump(config, f, indent=4, ensure_ascii=False)
        
        logger.info(f"数据库配置已保存: 数据库类型={db_type}")
        
        # 返回成功响应
        return templates.TemplateResponse(
            "db_config_editor.html",
            {
                "request": request,
                "config": config,
                "message": "配置保存成功!"
            }
        )
        
    except Exception as e:
        logger.error(f"保存配置失败: {str(e)}")
        config = get_current_config()
        return templates.TemplateResponse(
            "db_config_editor.html",
            {
                "request": request,
                "config": config,
                "message": f"保存失败: {str(e)}"
            }
        )

# 获取配置API（用于AJAX请求）
@router.get("/api/get_config")
async def get_config_api():
    """
    以JSON格式返回当前配置
    """
    try:
        config = get_current_config()
        return JSONResponse(content=config)
    except Exception as e:
        logger.error(f"获取配置失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# 测试数据库连接
@router.post("/api/test_db_connection")
async def test_db_connection(
    db_type: str = Form(...),
    sqlite_path: str = Form(None),
    mysql_host: str = Form(None),
    mysql_port: str = Form(None),
    mysql_user: str = Form(None),
    mysql_password: str = Form(None),
    mysql_db_name: str = Form(None)
):
    """
    测试数据库连接
    """
    try:
        if db_type == "mysql":
            # 尝试导入MySQL驱动
            try:
                import pymysql
                import sqlalchemy
                
                # 构建连接字符串
                port = int(mysql_port) if mysql_port else 3306
                connection_string = f"mysql+pymysql://{mysql_user}:{mysql_password}@{mysql_host}:{port}/{mysql_db_name}"
                
                # 测试连接
                engine = sqlalchemy.create_engine(connection_string)
                with engine.connect():
                    pass
                
                return JSONResponse(content={"success": True, "message": "MySQL连接成功!"})
                
            except ImportError:
                return JSONResponse(content={"success": False, "message": "缺少MySQL驱动，请安装pymysql"})
            except Exception as e:
                return JSONResponse(content={"success": False, "message": f"MySQL连接失败: {str(e)}"})
        
        elif db_type == "sqlite":
            try:
                import sqlite3
                
                # 确保目录存在
                if sqlite_path:
                    os.makedirs(os.path.dirname(os.path.abspath(sqlite_path)), exist_ok=True)
                
                # 测试连接
                conn = sqlite3.connect(sqlite_path or os.path.join(current_dir, "trade_monitor.db"))
                conn.close()
                
                return JSONResponse(content={"success": True, "message": "SQLite连接成功!"})
                
            except Exception as e:
                return JSONResponse(content={"success": False, "message": f"SQLite连接失败: {str(e)}"})
        
        else:
            return JSONResponse(content={"success": False, "message": "不支持的数据库类型"})
            
    except Exception as e:
        logger.error(f"测试数据库连接失败: {str(e)}")
        return JSONResponse(content={"success": False, "message": str(e)})

# 初始化函数
@router.on_event("startup")
async def startup_event():
    """
    路由启动时的初始化
    """
    logger.info("数据库配置路由模块已初始化")

# 导出路由
__all__ = ["router"]